package model

import (
	"database/sql/driver"
	"encoding/json"
	"fmt"
	"gozero-demo/internal/types"
)

type SubjectDataList []types.SubjectData

// Value 实现 sql.Scanner 接口，给数据库中写入JSON数据
func (m SubjectDataList) Value() (driver.Value, error) {
	if len(m) == 0 {
		return nil, nil
	}
	return json.Marshal(m)
}

// Scan 实现 sql.Scanner 接口，从数据库中读取数据并解析为JSON类型
func (m *SubjectDataList) Scan(value any) error {
	if value == nil {
		return nil
	}
	var bytes []byte
	switch v := value.(type) {
	case []byte:
		bytes = v
	case string:
		bytes = []byte(v)
	default:
		return fmt.Errorf("unsupported type: %T", value)
	}
	return json.Unmarshal(bytes, m)
}
